package com.xyh.gulimall.search.thread;


import java.util.concurrent.*;

public class ThreadTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.继承Thread
        new Thread(()->{
            System.out.println("f1");
        }).start();
        //2.实现Runnable
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("f2");
            }
        }).start();
        //3.实现 Callable 接口 + FutureTask （可以拿到返回结果，可以处理异常）
        FutureTask<Integer> f3 = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return null;
            }
        });
        new Thread(f3).start();

        //4.线程池
//        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
//                200,
//                10,
//                TimeUnit.SECONDS,
//                new LinkedBlockingDeque<>(10000),
//                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy());

        ExecutorService executor = Executors.newFixedThreadPool(10);


        CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程："+Thread.currentThread().getId());
            int i = 10 /5;
            System.out.println("运行结果：" + i);
            return i;
        },executor).whenComplete((res,excption)->{
            //虽然能得到异常信息，但是没法修改返回数据
            System.out.println("结果是：" + res + "异常是："+ excption);
        }).exceptionally(throwable -> {
            //可以感知异常，同时返回默认值
            return 10;
        });

        CompletableFuture.supplyAsync(()->{
            System.out.println("当前线程："+Thread.currentThread().getId());
            int i = 10 /5;
            System.out.println("运行结果：" + i);
            return i;
        },executor).handle((res,thr)->{
            if (res != null){
                return res * 2;
            }
            if (thr != null){
                return 0;
            }
            return 0;
        });

        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 5;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).thenApplyAsync((res) -> {

            return "HELLO" + res;
        }, executor);

        CompletableFuture<String> c1 = CompletableFuture.supplyAsync(() -> {
            return "1";
        }, executor);

        CompletableFuture<String> c2 = CompletableFuture.supplyAsync(() -> {
            return "2";
        }, executor);

        CompletableFuture<String> c3 = CompletableFuture.supplyAsync(() -> {
            return "3";
        }, executor);

        CompletableFuture<Void> allOf = CompletableFuture.allOf(c1, c2, c3);
        allOf.get();
    }
}
